<template>
  <div class="pop-up">
    <div class="tips">
      <div class="complete">完善收货地址：</div>
      <el-select v-model="provincesValue" class="select" placeholder="请选择省份">
        <el-option
          v-for="item in provinces"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-select v-model="citiesValue" class="select" placeholder="请选择城市">
        <el-option
          v-for="item in cities"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-select v-model="districtsValue" class="select" placeholder="请选择区域">
        <el-option
          v-for="item in districts"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-input
        v-model="keyword"
        placeholder="请输入具体地址"
        class="address"
      />
      <el-button type="primary" class="search-btn" @click="handlerSearch">搜索</el-button>
    </div>
    <div class="map-container">
      <baidu-map :center="center" :zoom="zoom" class="map" @click="clickEvent" @ready="handler">
        <!-- 自定义控件  -->
        <bm-control id="searAdressBox">
          <!-- 搜索列表 -->
          <div class="address-list">
            <div class="current-location">当前定位</div>
            <!-- 动态渲染搜索地址列表 -->
            <div style="padding-left: 20px;color: darkgoldenrod">
              <span v-text="curLocationInfo.receiveAddress" />
            </div>
            <div v-for="(item,index) in searchAddressList" :key="index" class="address-item" :style="item.latitude === lat && item.longitude === lng ? 'color: #ff3b30ff' : ''" @click="chooseAddress(item,index)">
              <!-- <div :class="xxxx? circle : .circle-grey"></div> -->
              <div :class="item.latitude === lat && item.longitude === lng ? 'circle' : 'circle-grey'" />
              <div class="keyword" v-text="item.receiveAddress">裕辉商务中心</div>
              <div class="address-detail" v-text="item.addressTitle">广东省广州市天河区涌东路20号</div>
            </div>
          </div>
        </bm-control>
        <bm-scale anchor="BMAP_ANCHOR_BOTTOM_RIGHT" :offset="{ width: 80, height: 3 }" />
        <bm-geolocation
          anchor="BMAP_ANCHOR_BOTTOM_RIGHT"
          :offset="{ height: 50, width: 10 }"
          :show-address-bar="true"
          :auto-location="true"
        />
        <bm-marker :position="center" :dragging="true" />
        <bm-view class="map" />

        <!-- <bm-local-search
          :keyword="keyword"
          :auto-viewport="true"
          :location="center"
        ></bm-local-search> -->
      </baidu-map>
    </div>

    <div class="footer">
      <el-button type="primary" class="concel" @click="concel">取消</el-button>
      <el-button class="save" @click="submitMap">确认选择</el-button>
    </div>
  </div>
</template>
<script>
// 引入省市区数据
import { listAddress, privinceList } from '@/js/provinceData'
export default {
  props: {
    location: {
      type: Object,
      required: false
    }
  },
  data() {
    return {
      keyword: '',
      myProvinceList: privinceList,
      myCities: listAddress,
      myDistricts: [],
      provinces: [],
      provincesValue: '',
      cities: [],
      citiesValue: '',
      districts: [],
      cityIndex: 0,
      districtsValue: '',
      showCityPopup: false,
      province: '',
      city: '',
      center: { lat: 116.404, lng: 39.915 },
      zoom: 15,
      BMap: null,
      // keyword: '',
      searchAddressList: [],
      lat: 116.397128,
      lng: 39.916527,
      latitude: '',
      longitude: '',
      map: null,
      geolocation: null,
      provinceInfo: '',
      geoCoder: null,
      pageParams: {
        index: 1,
        size: 20
      },
      curLocationInfo: {
        id: '',
        receiveProvince: '',
        receiveCity: '',
        receiveDistrict: '',
        receiveAddress: '',
        latitude: '',
        longitude: '',
        receiverName: '',
        receiverPhone: '',
        addressTitle: ''
      },
      selectAddress: {}
    }
  },
  watch: {
    provincesValue(val) {
      this.initCities(val)
    },
    citiesValue(val) {
      this.initDistricts(val)
    }
  },
  created() {
    this.initProvince()
  },
  methods: {
    handler({ BMap, map }) {
      this.map = map
      this.zoom = 20
      this.BMap = BMap
      this.geolocation = new BMap.Geolocation()
      this.geoCoder = new window.BMap.Geocoder()
      this.map.enableScrollWheelZoom(true) // 启用滚轮放大缩小，默认禁用
      this.map.enableContinuousZoom(true) // 启用地图惯性拖拽，默认禁用
      this.map.enablePinchToZoom(false) // 启用双指缩放地图
      this.map.setMinZoom(5) // 设置地图允许的最小级别。取值不得小于地图类型所允许的最小级别
      this.map.setMaxZoom(20) // 设置地图允许的最大级别。取值不得大于地图类型所允许的最大级别
      const lat = this.location.lat
      const lng = this.location.lng
      let pt = new window.BMap.Point(lng, lat)
      if (!lat || !lng) {
        pt = null
      }
      var locationOptions = {
        poiRadius: 3000,
        numPois: 10
      }
      this.geolocation.getCurrentPosition(r => {
        if (this.geolocation.getStatus() === 0) {
          // alert('您的位置：' + r.point.lng + ',' + r.point.lat + '---------' + this.geolocation.getStatus())
        } else {
          // alert('failed' + this.geolocation.getStatus())
          pt = new window.BMap.Point(this.lng, this.lat)
        }
        const point = pt || r.point
        this.lng = point.lng
        this.lat = point.lat
        this.center.lng = this.lng
        this.center.lat = this.lat
        const address = r.address
        // this.province = address.province
        this.provincesValue = address.province.replace('省', '').replace('市', '')
        this.citiesValue = address.city.replace('市', '')
        // this.city = address.city.replace('市', '')
        let location = address.province + '-' + address.city
        if (address.district) {
          this.districtsValue = address.district
          location += '-' + address.district
          this.curLocationInfo.receiveDistrict = address.district
        }
        this.provinceInfo = location
        let receiveAddress = ''
        if (address.street) {
          location += '-' + address.street
          receiveAddress += address.street
        }
        if (address.streetNumber) {
          location += '-' + address.streetNumber
          receiveAddress += address.streetNumber
        }
        // 封装当前地址数据
        this.curLocationInfo.receiveProvince = address.province
        this.curLocationInfo.receiveCity = address.city
        this.curLocationInfo.addressTitle = location.replace('-', '')
        this.curLocationInfo.receiveAddress = receiveAddress
        this.curLocationInfo.latitude = point.lat
        this.curLocationInfo.longitude = point.lng
        // 初始化一些地址
        var locationOptions = {
          poiRadius: 3000,
          numPois: 10
        }
        this.geoCoder.getLocation(point, rs => {
          const searchAddress = []
          rs.surroundingPois.forEach(i => {
            const { province, city, district } = rs.addressComponents
            this.provincesValue = province.replace('省', '').replace('市', '')
            this.citiesValue = city.replace('市', '')
            this.districtsValue = district
            const { address, title, point } = i
            searchAddress.push({
              receiveProvince: province,
              receiveCity: city,
              receiveDistrict: district,
              addressTitle: address,
              receiveAddress: title,
              latitude: point.lat,
              longitude: point.lng
            })
          })
          this.searchAddressList = searchAddress
        }, locationOptions)
        // 清除地图上所有的覆盖物
        this.map.clearOverlays()
        // 把标注添加到地图上
        this.map.addOverlay(new BMap.Marker(point))
      }, locationOptions)
    },
    // 点击地图监听
    clickEvent(e) {
      // 点击地图，使地址搜索框失焦
      // document.getElementById('addressSearch').blur()
      const point = e.point
      var locationOptions = {
        poiRadius: 3000,
        numPois: 10
      }
      this.geoCoder.getLocation(point, rs => {
        // addressComponents对象可以获取到详细的地址信息
        const addComp = rs.addressComponents
        this.province = addComp.province.replace('省', '')
        this.city = addComp.city.replace('市', '')
        this.provincesValue = addComp.province.replace('省', '').replace('市', '')
        this.citiesValue = addComp.city.replace('市', '')
        let location = addComp.province + '-' + addComp.city
        if (addComp.district) {
          location += '-' + addComp.district
          this.districtsValue = addComp.district
        }
        if (addComp.street) {
          location += '-' + addComp.street
        }
        if (addComp.streetNumber) {
          location += '-' + addComp.streetNumber
        }
        // 设置对应的值
        this.lat = point.lat
        this.lng = point.lng
        if (rs.surroundingPois.length > 0) {
          this.curLocationInfo.receiveAddress = rs.surroundingPois[0].title
        } else {
          this.curLocationInfo.receiveAddress = rs.address
        }
        // 封装数据
        this.curLocationInfo.latitude = point.lat
        this.curLocationInfo.longitude = point.lng
        this.curLocationInfo.receiveProvince = addComp.province
        this.curLocationInfo.receiveCity = addComp.city
        this.curLocationInfo.receiveDistrict = addComp.district
        this.curLocationInfo.addressTitle = location.replace('-', '')

        // 获取地址列表
        const searchAddress = []
        if (rs.surroundingPois.length > 0) {
          rs.surroundingPois.forEach(i => {
            const { province, city, district } = rs.addressComponents
            this.city = city.replace('市', '')
            const { address, title, point } = i
            searchAddress.push({
              receiveProvince: province,
              receiveCity: city,
              receiveDistrict: district,
              addressTitle: address,
              receiveAddress: title,
              latitude: point.lat,
              longitude: point.lng
            })
          })
        } else {
          const { addressComponents, address, point } = rs
          const { province, city, district, street, streetNumber } = addressComponents
          if (street && streetNumber) {
            searchAddress.push({
              receiveProvince: province,
              receiveCity: city,
              receiveDistrict: district,
              addressTitle: address,
              receiveAddress: street + streetNumber,
              latitude: point.lat,
              longitude: point.lng
            })
          }
        }
        this.searchAddressList = searchAddress
      }, locationOptions)
      // 清除地图上所有的覆盖物
      this.map.clearOverlays()
      // 把标注添加到地图上
      this.map.addOverlay(new BMap.Marker(point))
    },
    // 关键字搜索地址
    handlerSearch() {
      if (!this.keyword) {
        this.$message.error('搜索具体地址不能为空')
        return
      }
      var arr = []
      var options = {
        onSearchComplete: results => {
          // 封装数据
          for (let i = 0; i < results.getCurrentNumPois(); i++) {
            const item = results.getPoi(i)
            var addressInfo = {}
            addressInfo.receiveProvince = item.province
            addressInfo.receiveCity = item.city
            addressInfo.addressTitle = item.address
            addressInfo.receiveAddress = item.title
            addressInfo.latitude = item.point.lat
            addressInfo.longitude = item.point.lng
            // 获取区信息
            this.geoCoder.getLocation(item.point, rs => {
              addressInfo.receiveDistrict = rs.addressComponents.district
            })
            arr.push(addressInfo)
          }
          this.map.setZoom(15)
          this.searchAddressList = arr
          // 用经纬度设置地图中心点
          this.map.clearOverlays()
          const lat = arr.length > 0 ? arr[0].latitude : this.lat
          const lng = arr.length > 0 ? arr[0].longitude : this.lng
          var newPoint = new window.BMap.Point(lng, lat)
          var marker = new window.BMap.Marker(newPoint) // 创建标注
          this.map.addOverlay(marker) // 将标注添加到地图中
          this.map.panTo(newPoint)
        }
      }
      var local = new BMap.LocalSearch(this.map, options)
      local.gotoPage(this.pageParams.index) // 设置分页
      local.setPageCapacity(this.pageParams.size) // 设置每页条数
      if (this.citiesValue) {
        local.setLocation(this.citiesValue)
      } else {
        if (this.provincesValue) {
          local.setLocation(this.provincesValue)
        }
      }
      let keyword = this.keyword
      if (this.districtsValue) {
        keyword = this.districtsValue + keyword
      }
      local.search(keyword)
    },
    // 选择地址
    chooseAddress(item, index) {
      this.lng = item.longitude
      this.lat = item.latitude
      // 处理详细地址
      const address = JSON.parse(JSON.stringify(item))
      address.receiveAddress = address.addressTitle.replace(/-/g, '').replace(address.receiveProvince, '').replace(address.receiveCity, '').replace(address.receiveDistrict, '').replace(address.receiveAddress, '') + address.receiveAddress
      const index1 = address.receiveAddress.indexOf(';') || address.receiveAddress.indexOf('；')
      if (index1 !== -1) {
        address.receiveAddress = address.receiveAddress.substr(0, index1)
      }
      if (!address.receiveDistrict) {
        address.receiveDistrict = ''
      }
      this.selectAddress = address
    },
    // 初始化省份信息
    initProvince() {
      const arr = []
      this.myProvinceList.forEach(i => {
        const privince = {
          label: i,
          value: i
        }
        arr.push(privince)
      })
      this.provinces = arr
    },
    // 初始化城市信息
    initCities(val) {
      this.citiesValue = ''
      if (val) {
        const index = this.myProvinceList.indexOf(val)
        this.cityIndex = index
        const arr = []
        this.myCities[index].city.forEach(i => {
          const city = {
            label: i.name,
            value: i.name
          }
          arr.push(city)
        })
        this.cities = arr
      }
    },
    // 初始化区数据
    initDistricts(val) {
      this.districtsValue = ''
      if (val) {
        const list = this.myCities[this.cityIndex].city.filter(i => i.name === val)
        const arr = []
        list[0].area.forEach(i => {
          const district = {
            label: i,
            value: i
          }
          arr.push(district)
        })
        this.districts = arr
        if (val !== '') {
        // 用城市名设置地图中心点
          this.map.centerAndZoom(val)
        }
      }
    },
    submitMap() {
      if (Object.keys(this.selectAddress).length === 0) {
        this.$message.error('请先选择收货地址')
        return
      }
      this.$emit('submitMap', this.selectAddress)
    },
    concel() {
      this.$emit('concel')
    }
  }
}
</script>

<style scoped lang="scss">
  .save {
    width: 110px;
    height: 37px;
    background-color: #ff3b30;
    color: #fff;
    border: none;
  }
  .concel {
    width: 110px;
    height: 37px;
    background-color: #f5f5f5;
    color: #6b6b6bff;
    border: 1px solid #e5e5e5ff;
  }
  .search-btn {
    width: 60px;
    height: 28px;
    color: #ff3b30ff;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #fff4f3;
    border: 1px solid #ff3b30ff;
    line-height: 0;
    margin-left: 15px;
  }
  .search-btn:hover {
    width: 60px;
    height: 28px;
    color: #ff3b30ff;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #fff4f3;
    border: 1px solid #ff3b30ff;
    line-height: 0;
  }
  #searAdressBox {
    position: absolute;
    top: 24px !important;
    left: 20px !important;
    z-index: 1000;
    width: 282px;

    display: flex;
    box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.2);
    background-color: #fff;
    .address-list {
      border-bottom: 1px solid #e5e5e5ff;
      background-color: #fff;
      .current-location {
        font-weight: 700;
        background-color: #fff;
        // margin-bottom: 10px;
        width: 282px;
        height: 40px;
        line-height: 40px;
        padding-left: 20px;
      }

      .address-item {
        width: 282px;
        font-size: 12px;
        background-color: #fff;

        text-align: left;
        height: 50px;
        padding: 7px 0 7px 20px;
        padding-left: 20px;
        /*color: #ff3b30ff;*/
        border-top: 1px solid #e5e5e5ff;
        padding-bottom: 10px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        flex-direction: column;
        position: relative;
        .address-detail {
          width: 262px;
        }
        .keyword {
          width: 262px;
          margin-bottom: 5px;
        }
        .circle {
          width: 6px;
          height: 6px;
          border-radius: 3px;
          background-color: #ff3b30ff;
          position: absolute;
          top: 22px;
          left: 8px;
        }
        .circle-grey {
          width: 6px;
          height: 6px;
          border-radius: 3px;
          background-color: #333333;
          position: absolute;
          top: 22px;
          left: 8px;
        }
      }
    }
  }

  .pop-up {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 100;
    background: rgba(54, 39, 39, 0.5);
    display: flex;
    justify-content: center;
    flex-direction: column;
    align-items: center;
    .tips {
      width: 1187px;
      height: 50px;
      line-height: 50px;
      background-color: #fff;
      box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.2);
      padding: 0 20px;
      color: #3d3d3dff;
      display: flex;
      justify-content: start;
      align-items: center;
      z-index: 100;
      ::v-deep .el-input__suffix {
        right: 2px;
        top: 0px;
      }
      ::v-deep .el-input__icon{
        color: #C0C4CC!important;
      }
      ::v-deep .el-input__inner {
        width: 128px;
        height: 30px;
        margin-right: 15px;
      }
      ::v-deep .el-select {
        width: 128px;
        height: 50px;
        margin-right: 15px;
      }
      .address {
        width: 233px !important;
        height: 50px;
        ::v-deep .el-input__inner {
          width: 100%;
          height: 30px;
          margin-right: 15px;
        }
      }

      .complete {
        margin-right: 75px;
        height: 50px;
        color: #3d3d3dff;
        font-weight: 700;
        font-size: 16px;
      }
    }
    .map-container {
      .map {
        width: 1187px;
        height: 530px;
        position: relative;
      }
    }

    .footer {
      width: 1187px;
      height: 87px;
      background-color: #fff;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    /deep/ .select{
      .el-input__inner{
        text-indent: 4px;
      }
      .el-select__caret{
            height: 35px;
            width: 15px;
      }
    }
  }
</style>
